<template>
  <div class="custom-add-ctn">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="goBack" />
    <van-form ref="form" @submit="onSumit">
      <div class="formData">
        <van-field clickable required :rules="[{ required: true }]" name="showOrgName" :value="formData.showOrgName" label="所属展厅" placeholder="请选择" input-align="right" right-icon="arrow" @click="onPicker(showOrgList, 'showOrgName', 'showOrgId')" />
        <van-field clickable required :rules="[{ required: true }]" name="empName" :value="formData.empName" label="所属销售顾问" placeholder="请选择" input-align="right" right-icon="arrow" @click="onPicker(serviceColumns, 'empName', 'empId')" />
        <van-field v-model="formData.name" required :rules="[{ required: true }]" name="name" label="客户姓名" input-align="right" placeholder="请输入客户姓名" />
        <van-field v-model="formData.mobile" required :rules="[{ required: true }]" name="mobile" label="联系电话" input-align="right" placeholder="请输入客户联系电话" type="tel" />
        <van-field required :rules="[{ required: true }]" name="rbmale" label="性别" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.rbmale" direction="horizontal">
              <van-radio name="1" icon-size="16px">男</van-radio>
              <van-radio name="0" icon-size="16px">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field clickable required :rules="[{ required: true }]" name="channel" :value="formData.channel" label="来源渠道" placeholder="请选择" input-align="right" right-icon="arrow" @click="onPicker(channelColumns, 'channel', 'sourceChannelId')" />
        <van-field clickable required :rules="[{ required: true }]" name="SHCustomerName" :value="formData.SHCustomerName" label="二手车需求" placeholder="请选择" input-align="right" right-icon="arrow" @click="onPicker(SHCustomerColumns, 'SHCustomerName', 'SHCustomer')" />
        <van-field clickable required :rules="[{ required: true }]" name="serialName" :value="formData.serialName" label="意向车系" placeholder="请选择" input-align="right" right-icon="arrow" @click="onPicker(serialColumns, 'serialName', 'intentionModelId')" />
        <van-field clickable name="carStockName" :value="formData.carStockName" label="意向车源" placeholder="请选择" input-align="right" right-icon="arrow" @click="handleMoreSelect('carStockId', 'carStockName')" />
        <van-field v-if="!leadsId" clickable name="saleLead" :value="formData.saleLead" label="销售线索" placeholder="请选择" input-align="right" right-icon="arrow" @click="onPicker(saleLeadColumns, 'saleLead', 'saleLeadsId')" />
        <!-- 意向级别选择弹窗 -->
        <van-popup v-model="showPicker" position="bottom">
          <van-field v-if="showSearch" name="模糊查询" input-align="left" v-model="likeWho" label="模糊查询" placeholder="请输入模糊查询关键词" />
          <van-picker show-toolbar :columns="columns" @confirm="onPickerConfirm" @cancel="showPicker = false" value-key="name" />
        </van-popup>
      </div>
      <div v-if="leadsId" class="lead">
        <van-checkbox v-model="linkLead" shape="square" icon-size="14px" @change="onCheckboxChange">当前关联线索</van-checkbox>
        <div class="row">
          <span class="label">客户名称：</span>
          <span class="value">{{ leadInfo.customerName }}</span>
        </div>
        <div class="row">
          <span class="label">商机来源：</span>
          <span class="value">{{ leadInfo.webType }}</span>
        </div>
        <div class="row">
          <span class="label">联系电话：</span>
          <span class="value">{{ leadInfo.phone }}</span>
        </div>
      </div>
      <div class="btn" @click="onSumit">确认</div>
    </van-form>
    <van-popup v-model="showSelectCarStockId">
      <inventory-manage :showOrgId="formData.showOrgId" @getcarStock="getcarStock" @cancel="showSelectCarStockId = false" @clearlSelect="
          formData.carStockId = ''
          formData.carStockName = ''
          showSelectCarStockId = false
        "></inventory-manage>
    </van-popup>
  </div>
</template>

<script>
import { Dialog } from "vant";
import sellManageApi from "@/api/sellManageApi";
import commonApi from "@/api/commonApi";
import inventoryManage from "../salesLeads/inventoryManage";

const { secondHandCarFacade, getEnums } = sellManageApi;
export default {
  components: {
    inventoryManage
  },
  data() {
    return {
      // 客户信息
      formData: {
        showOrgName: "", // 展厅
        showOrgId: "", // 展厅ID
        empName: "", // 所属销售顾问
        empId: "", // 所属销售顾问ID
        name: "", // 客户姓名
        mobile: "", // 客户联系电话
        rbmale: "", // 性别
        // webType: '', // 来源渠道
        SHCustomerName: "", // 二手车需求
        SHCustomer: "", // 二手车需求
        serialName: "", // 意向车系
        carStockName: "", // 意向车源
        saleLead: "" // 销售线索
      },
      // formData: {
      //   showOrgName: '', // 展厅
      //   empName: '王某某', // 所属销售顾问
      //   name: '王某某', // 客户姓名
      //   mobile: '王某某', // 客户联系电话
      //   rbmale: '1', // 性别
      //   webType: '垂直媒体-懂车帝', // 来源渠道
      //   SHCustomer: '垂直媒体-懂车帝', // 二手车需求
      //   serialName: 'CT5', // 意向车系
      //   carStockName: 'CT5', // 意向车源
      //   saleLead: 'CT5', // 销售线索
      // },
      showCalendar: false, // 是否展示日历
      columns: [],
      originalColumns: [],
      // 展厅列表
      showOrgList: [],
      // 销售顾问列表
      serviceColumns: [],
      serviceColumns1: [
        { name: "黄某某", billId: "fH84grBwSDSY0oCGgCcSCBO33n8=" },
        { name: "张某某", billId: "fH84grBwSDSY0oCGgCcSCBO33n8=" }
      ],
      // 来源渠道列表
      channelColumns: [],
      // 二手车列表
      SHCustomerColumns: [],
      // 意向车系列表
      serialColumns: [
        {
          billId: "123", //单据id
          number: "", //编码
          name: "test1", //名称
          brandName: "" //品牌名称
        },
        {
          billId: "124", //单据id
          number: "", //编码
          name: "test2", //名称
          brandName: "" //品牌名称
        }
      ],
      // 意向来源列表
      sourceColumns: [],
      // 销售线索列表
      saleLeadColumns: [],
      // 战败原因
      showPicker: false, // 是否展示意向级别选择弹窗
      pickerName: "", // 当前使用picker的文本字段
      pickerId: "", // 当前使用picker的ID字段
      leadInfo: {
        customerName: "琳琳临",
        webType: "是否展示意向级别选择弹窗",
        phone: "13600136001"
      },
      linkLead: true, // 是否关联线索
      leadsId: "", // 线索ID
      likeWho: "",
      showSelectCarStockId: false
    };
  },
  computed: {
    // 是否展示搜索
    showSearch() {
      const arr = ["showOrgName", "empName", "serialName"];
      return arr.includes(this.pickerName);
    }
  },
  watch: {
    // likeWho: function (nval, oval) {
    //   if (nval) {
    //     let newArr = this.showOrgList.filter((item) => {
    //       return item.name.indexOf(nval) > -1
    //     })
    //     // console.log(newArr)
    //     this.columns = newArr
    //   } else {
    //     this.columns = this.showOrgList
    //   }
    // },
    likeWho: function(nval, oval) {
      console.log("nval:", nval);
      if (nval) {
        let newArr = this.originalColumns.filter(item => {
          return item.name.toLowerCase().indexOf(nval) > -1;
        });
        // console.log(newArr)
        this.columns = newArr;
      } else {
        this.columns = this.originalColumns;
      }
      console.log("this.column:", this.columns);
    }
  },
  async mounted() {
    // 获取展厅列表
    const org = await this.getShowOrgByUser();
    console.log("org:", org);
  },
  methods: {
    goBack() {
      this.$router.replace({
        path: "/customManage",
        query: { reload: 1 }
      });
    },
    // 获取关联意向车辆信息
    getcarStock(data) {
      this.formData.carStockId = data.carStockId;
      this.formData.carStockName = data.carStockName;
      this.showSelectCarStockId = false;
    },
    // 关联意向车辆
    handleMoreSelect() {
      if (this.formData.showOrgId) {
        this.showSelectCarStockId = true;
      } else {
        this.$toast.fail("请先选择展厅");
      }
    },
    // 根据方法名获取数据
    async getDatas(params) {
      const res = await secondHandCarFacade(params);
      console.log("resss:", res);
      if (res.code !== 1) {
        // this.$toast.fail({ message: `${params.field}${res.msg}`, duration: 150000 })
      }
      return res.data;
    },
    // 根据key值获取枚举值
    async getEnumList(key) {
      const res = await getEnums({
        key //固定值
      });
      return res.data;
    },
    // 保持选中
    onCheckboxChange(event) {
      this.linkLead = true;
    },
    // 获取来源渠道
    async getChannelList() {
      console.log("获取来源渠道");
      this.channelColumns = await this.getDatas({ method: "getSourceChannel" });
    },
    // 二手车需求
    async getSHCustomerList() {
      console.log("二手车需求");
      this.SHCustomerColumns = await this.getEnumList("SHCustomer");
      this.SHCustomerColumns = this.SHCustomerColumns.filter(
        e => e.name !== "无"
      );
      const defaultChoice = this.SHCustomerColumns.filter(
        e => e.name === "买二手车"
      );
      this.formData.SHCustomerName = defaultChoice[0].name;
      this.formData.SHCustomer = defaultChoice[0].value;
    },
    // 意向车系
    async getSerialList(orgId) {
      console.log("意向车系");
      this.serialColumns = await this.getDatas({
        method: "getModelTypeEntry",
        brandId: orgId,
        field: "意向车系"
      });
      console.log("意向车系", this.serialColumns);
      if (!this.serialColumns || this.serialColumns.length < 1) {
        this.$toast.fail("意向车系所获取的数据为空，请联系开发人员");
      }
    },
    // 意向车源
    async getCarSourceList(showOrgId) {
      console.log("意向车源");
      // this.sourceColumns = await this.getDatas({ method: 'getCarStockList', showOrgId })
      const requestParams = {
        method: "getCarStockList",
        codeNo: "", //车架号，非必填，String
        pageNo: 1, //页码，非必填，String
        userId: "", //用户ID，必填，String
        orgId: "", //登录组织Id，必填，String
        stockStartDate: "", //入库开始时间，非必填，String
        stockEndDate: "", //入库结束时间，非必填，String
        brandId: "", //品牌ID，非必填，String
        showOrgId, //展厅ID，非必填，String
        isGenContract: "", //是否生成销售合同，非必填，String
        billStatus: "", //库存状态，非必填，String
        isJySale: "" //是否寄售车辆，非必填，String
      };
      this.sourceColumns = await this.getDatas(requestParams);
      this.sourceColumns = this.sourceColumns.map(e => {
        return {
          name: e.carNo,
          billId: e.billId
        };
      });
      console.log(this.sourceColumns);
    },
    // 获取销售线索接口
    async getLeadList(showOrgId) {
      this.saleLeadColumns = [];
      console.log("获取销售线索接口");
      let pageNo = 1;
      const requestParams = {
        method: "getSalesLeadsList",
        pageNo, //当前页数，默认从1开始，每页显示十条，int，不能为空或者小于1
        customerOrCarModel: "", //客户名称或意向车型，String
        leadsStartDate: "", //线索生成开始时间，String
        leadsEndDate: "", //线索生成结束时间，String
        clusState: "", //线索状态，String
        showOrgId, //所属展厅ID，String
        webType: "", //线索来源，String
        isAddCus: "0", //是否生成客户档案，String
        accountName: "" //分配销售顾问，String
      };
      let pageSize = 10;
      while (pageSize >= 10) {
        let saleLeadColumns = await this.getDatas(requestParams);
        requestParams.pageNo = requestParams.pageNo + 1;
        pageSize = saleLeadColumns.length;
        saleLeadColumns = saleLeadColumns.map(e => {
          return {
            name: e.customerName,
            billId: e.billId,
            leadsType: e.leadsTypeValue
          };
        });
        this.saleLeadColumns = [...this.saleLeadColumns, ...saleLeadColumns];
      }
      // this.saleLeadColumns = await this.getDatas(requestParams)
      // this.saleLeadColumns = this.saleLeadColumns.map(e => {
      //   return {
      //     name: e.customerName,
      //     billId: e.billId
      //   }
      // })
      console.log(this.saleLeadColumns);
    },
    // 根据用户获取对应展厅
    getShowOrgByUser() {
      secondHandCarFacade({
        method: "getShowOrgByUser", //固定值
        orgKey: "showOrg" // orgkey
      }).then(res => {
        if (res.data) {
          this.showOrgList = res.data;
          // this.showOrgList.forEach(e => {
          //   this.getSaleEmps(e)
          // });
          // this.showOrgList = res.data.filter(e => e.name === '厦门保时捷')
          this.initData();
        }
      });
    },
    initData() {
      if (localStorage.getItem("userInfo")) {
        this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
        this.formData.empName = this.userInfo.kdusername;
        this.formData.empId = this.userInfo.kdpersonid;
      }

      // 是否有线索参数，如果有，则根据线索生成客档
      if (this.$route.query.id) {
        this.leadsId = this.$route.query.id;
        this.getLeadDetail(this.leadsId);
      }
      // // 3、获取来源渠道 （未知）
      this.getChannelList();
      // // 4、二手车需求 （未知）
      this.getSHCustomerList();
    },
    // 获取根据展厅获取销售顾问
    async getSaleEmps(orgId) {
      console.log("获取根据展厅获取销售顾问");
      const res = await commonApi.getEmpPerson({
        fixCenterId: orgId,
        type: "saleEmp"
      });
      // const res = await commonApi.getEmpPerson({ fixCenterId: e.billId })
      // console.log('获取根据展厅获取销售顾问res:', res)
      this.serviceColumns = res.data;
      // if (res.data.length > 0) {
      //   console.log('销售顾问：', e.name)
      // }
    },
    // 获取线索详情
    getLeadDetail(billId) {
      secondHandCarFacade({
        method: "getSalesLeadsById", //固定值
        billId
      }).then(res => {
        this.leadInfo = res.data;
        // this.formData = this.leadInfo
        this.formData.showOrgName = this.leadInfo.showOrgName;
        this.formData.showOrgId = this.leadInfo.showOrgId;
        this.formData.name = this.leadInfo.customerName;
        this.formData.saleLeadsId = this.leadsId;
        // this.formData.empName = this.leadInfo.accountName
        this.formData.mobile = this.leadInfo.phone;
        this.formData.rbmale = this.leadInfo.customerSex;
        this.formData.empName = this.userInfo.kdusername;
        this.formData.empId = this.userInfo.kdpersonid;
        // 要传leadsType，还是leadsTypeValue
        this.formData.leadsType = this.leadInfo.leadsTypeValue;
        // 根据展厅查询相关数据
        this.getDataWhenHallChange(this.leadInfo.showOrgId);
      });
    },
    // 单项选择
    onPicker(columns, pickerName, pickerId) {
      this.likeWho = "";
      const arr = ["empName", "carStockName", "saleLead", "serialName"];
      if (!this.formData.showOrgName && arr.includes(pickerName)) {
        this.$toast.fail("请先选择展厅");
        return;
      }
      if (pickerName === "serialName") {
        // this.getSerialList(this.formData.showOrgId)
      }
      // console.log('column:', columns)
      // console.log('pickerId:', pickerId)
      this.pickerName = pickerName;
      this.pickerId = pickerId;
      this.columns = columns;
      this.originalColumns = columns;
      this.showPicker = true;
    },
    // 下拉框选择确认
    onPickerConfirm(item) {
      console.log("item:", item);
      this.formData[this.pickerName] = item.name;
      this.formData[this.pickerId] = item.billId;
      if (this.pickerName === "channel") {
        this.formData[this.pickerName] = item[0] + "-" + item[1];
        const pList = this.channelColumns.filter(e => e.name === item[0]);
        this.formData[this.pickerId] = pList[0].children.filter(
          e => e.name === item[1]
        )[0].billId;
      } else if (this.pickerName === "SHCustomerName") {
        this.formData[this.pickerId] = item.value;
      } else if (this.pickerName === "showOrgName") {
        // 根据展厅查询相关数据
        this.getDataWhenHallChange(item.billId);
      } else if (this.pickerName === "saleLead") {
        this.formData.leadsType = item.leadsType;
      }

      this.showPicker = false;
    },
    // 根据展厅变动，需要查询的数据
    getDataWhenHallChange(orgId) {
      this.formData.serialName = "";
      this.formData.intentionModelId = "";
      this.formData.carStockName = "";
      this.formData.carStockId = "";
      this.formData.saleLead = "";
      this.formData.saleLeadsId = "";
      this.formData.empName = "";
      this.formData.empId = "";
      this.getSaleEmps(orgId);
      // this.getCarSourceList(orgId)
      if (!this.leadsId) {
        this.getLeadList(orgId);
      }
      // // 5、意向车系 （未知）
      this.getSerialList(orgId);
    },
    // 提交或保存时
    onSumit() {
      this.$refs.form
        .validate()
        .then(res => {
          // 校验手机号
          const pattern = /^1[3-9]\d{9}$/;
          const reg = /[\t\r\f\n\s]*/g;
          this.formData.mobile = this.formData.mobile.replace(reg, "");
          if (!pattern.test(this.formData.mobile)) {
            this.$toast.fail("请输入正确手机号");
            return;
          }
          Dialog.confirm({
            title: "确认提交？",
            confirmButtonColor: "#1684FC"
          })
            .then(async () => {
              // on confirm
              console.log("then");
              let formData = JSON.parse(JSON.stringify(this.formData));

              delete formData.showOrgName;
              delete formData.carStockName;
              delete formData.serialName;
              delete formData.saleLead;
              delete formData.empName;
              delete formData.channel;
              delete formData.SHCustomerName;

              formData.method = "addCustomer";
              if (this.leadsId) {
                formData.saleLeadsId = this.leadsId;
              }

              // TODO 测试代码
              // formData.empId = 'ZSIAAAMH50KA733t'
              // formData.empId = this.userInfo.kdpersonid
              // formData.leadsType = '3'
              // formData.rbfemale = '0'

              console.log("formData:", formData);
              const res = await secondHandCarFacade(formData);
              console.log("res:", res);
              // 成功返回客档列表, 并指定刷新页面
              if (res.code === 1) {
                this.$router.replace({
                  path: "/customManage",
                  query: { reload: 1 }
                });
              } else {
                this.$toast.fail(res.msg);
              }
            })
            .catch(() => {
              // on cancel
            });
        })
        .catch(err => {
          console.log("valid err:", err);
          this.$toast.fail("请完善信息");
        });
    }
  }
};
</script>

<style lang="less" scoped>
.custom-add-ctn {
  background-color: rgba(248, 248, 248, 1);
}
.lead {
  width: 80%;
  background: #fff;
  font-size: 14px;
  margin: auto;
  padding: 10px;
  margin-top: 25px;
  border-radius: 10px;
  .row {
    margin-top: 5px;
    .value {
      color: rgba(108, 108, 108, 1);
    }
  }
}
.btn {
  width: 60%;
  background: #1684fc;
  color: #fff;
  font-size: 15px;
  margin: auto;
  border-radius: 20px;
  padding: 10px;
  text-align: center;
  margin-bottom: 25px;
  margin-top: 25px;
}
.van-radio--horizontal {
  margin: 0 0 0 10px;
}
</style>